# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     RedisClient
   Description :  封装Redis相关操作
   Author :        William
   date：          2020.2.19
-------------------------------------------------
   Change Activity:
                   2020.2.19: 封装Redis相关操作
-------------------------------------------------
"""
__author__ = 'William'

import json
from Config.Setting import Pool,PROXY_NAME
from redis import Redis


class RedisClient(object):
    """
    Redis client 和SSDB协议一致 数据结构一致, 但部分方法不通用

    Redis中代理存放的结构为hash：
        原始代理存放在name为raw_proxy的hash中, key为代理的ip:por, value为代理属性的字典;
        验证后的代理存放在name为useful_proxy的hash中, key为代理的ip:port, value为代理属性的字典;

    """

    def __init__(self,PROXY_NAME,Pool):
        self.name = PROXY_NAME
        self.__conn = Redis(connection_pool=Pool)

    def get(self, proxy_str):
        """
        从hash中获取对应的proxy
        :param proxy_str: proxy str
        :return:
        """
        data = self.__conn.hget(name=self.name, key=proxy_str)
        if data:
            return data.decode('utf-8')
        else:
            return None

    def put(self, proxy_dict):
        """
        将代理放入hash
        :param proxy_dict: 请参考Setting 配置文件的规则进行入库或者更新
        :return:
        """
        if isinstance(proxy_dict,dict):
            k = proxy_dict.get("proxy_ip",None)
            if k:
                data = self.__conn.hset(self.name, k, json.dumps(proxy_dict))
                return data

    def delete(self, proxy_str):
        """
        移除指定代理
        :param proxy_str: proxy str
        :return:
        """
        res = self.__conn.hdel(self.name, proxy_str)
        return res

    def exists(self, proxy_str):
        """
        判断指定代理是否存在
        :param proxy_str: proxy str
        :return:
        """
        return self.__conn.hexists(self.name, proxy_str)

    def update(self, proxy_dict):
        """
        更新 proxy 属性
        :param proxy_dict:请参考Setting 配置文件的规则进行入库或者更新
        :return:
        """
        if isinstance(proxy_dict, dict):
            k = proxy_dict.get("proxy_ip", None)
            if k:
                data = self.__conn.hset(self.name, k, json.dumps(proxy_dict))
                return data


    def pop(self):
        """
        弹出一个代理
        :return: dict {proxy: value}
        """
        # proxies = self.__conn.hkeys(self.name)
        # if proxies:
        #     proxy = random.choice(proxies)
        #     value = self.__conn.hget(self.name, proxy)
        #     self.delete(proxy)
        #     return {'proxy': proxy.decode('utf-8') if PY3 else proxy,
        #             'value': value.decode('utf-8') if PY3 and value else value}
        return None

    def getAll(self):
        """
        列表形式返回所有代理的key
        :return:
        """
        item_dict = self.__conn.hgetall(self.name)
        return [value.decode('utf8') for value in item_dict.values()]

    def clear(self):
        """
        清空所有代理
        :return:
        """
        return self.__conn.delete(self.name)

    def getNumber(self):
        """
        返回代理数量
        :return:
        """
        return self.__conn.hlen(self.name)

Redis_cliient = RedisClient(PROXY_NAME,Pool)
if __name__ == '__main__':
    # Redis_cliient.delete("39.137.69.7:80")
    p = {
       "proxy_ip":  "39.137.69.7:85",
       "type":1,
       "user":"",
       "password":"",
       "last_status":   1,
       "last_time":   "2020-02-19 13:41:58"
    }
    # Redis_cliient.put(p)
    Redis_cliient.update(p)